# app.py
from flask import Flask, jsonify
import requests
import re
app = Flask(__name__)

@app.route('/api/fund/<code>')
def fund(code):
    url = f'https://fundgz.1234567.com.cn/js/{code}.js'
    try:
        r = requests.get(url, timeout=5)
        text = r.text
        m = re.match(r'^\s*jsonpgz\(\s*(.*)\s*\)\s*;?\s*$', text, re.S)
        if not m:
            return jsonify({'error': 'unexpected response format'}), 502
        inner = m.group(1).strip()
        if not inner:
            return jsonify(None)
        data = requests.utils.json.loads(inner)  # or json.loads(inner)
        return jsonify(data)
    except Exception as e:
        return jsonify({'error': 'fetch error', 'detail': str(e)}), 500

if __name__ == '__main__':
    app.run(port=5000)
    
""" 
fetch('/api/fund/007467')
  .then(r => r.json())
  .then(data => console.log('proxied data', data))
  .catch(err => console.error(err));
"""
